/*
========================================================================
 Name        : FRamI_UIAppUi.cpp
 Author      : Lenka Litvova
 Copyright   : Copyright belongs to Lenka Litvova
 Description : 
========================================================================
*/
// [[[ begin generated region: do not modify [Generated System Includes]
#include <eikmenub.h>
#include <akncontext.h>
#include <akntitle.h>
#include <FRamI_UI.rsg>
// ]]] end generated region [Generated System Includes]

#include <stringloader.h>
#include <APGCLI.H> //TApaTask
#include "CamEngine.h"
#include "AudioPlayer.h"
#include "MessageSender.h"
#include "ImageSaver.h"
#include "BackgroundMonitor.h"
#include "PhoneProtector.h"
#include "Globals.h"

// [[[ begin generated region: do not modify [Generated User Includes]
#include "FRamI_UIAppUi.h"
#include "FRamI_UI.hrh"
#include "FRamI_UIMainContainer.hrh"
#include "FRamI_UISettingList.hrh"
#include "FRamI_UIUsersList.hrh"
#include "FRamI_UIMainContainerView.h"
#include "FRamI_UISettingListView.h"
#include "FRamI_UICameraContainerView.h"
#include "FRamI_UIUsersListView.h"
#include "FRamI_UIBrowserListView.h"
// ]]] end generated region [Generated User Includes]

// [[[ begin generated region: do not modify [Generated Constants]
// ]]] end generated region [Generated Constants]

/**
 * Construct the CFRamI_UIAppUi instance
 */ 
CFRamI_UIAppUi::CFRamI_UIAppUi():iPaused(EFalse), iBack(EFalse)
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	// ]]] end generated region [Generated Contents]
	
	}

/** 
 * The appui's destructor removes the container from the control
 * stack and destroys it.
 */
CFRamI_UIAppUi::~CFRamI_UIAppUi()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	// ]]] end generated region [Generated Contents]
	if(iLastUser)
	{
		delete iLastUser;
		iLastUser = NULL;
	}
	delete iRecManager;
	delete iPlayer;
	delete iImageSaver;
	delete iMonitor;
	delete iProtector;
	}

// [[[ begin generated function: do not modify
void CFRamI_UIAppUi::InitializeContainersL()
	{
	iFRamI_UIMainContainerView = CFRamI_UIMainContainerView::NewL();
	AddViewL( iFRamI_UIMainContainerView );
	SetDefaultViewL( *iFRamI_UIMainContainerView );
	CConfiguration *conf = CConfiguration::NewL();
	conf->LoadSettingFromFileL();
	iFRamI_UISettingListView = CFRamI_UISettingListView::NewL(conf);
	AddViewL( iFRamI_UISettingListView );
	iFRamI_UICameraContainerView = CFRamI_UICameraContainerView::NewL();
	AddViewL( iFRamI_UICameraContainerView );
	iFRamI_UIUsersListView = CFRamI_UIUsersListView::NewL();
	AddViewL( iFRamI_UIUsersListView );
	iFRamI_UIBrowserListView = CFRamI_UIBrowserListView::NewL();
	AddViewL( iFRamI_UIBrowserListView );
	
	}
// ]]] end generated function

/**
 * Handle a command for this appui (override)
 * @param aCommand command id to be handled
 */
void CFRamI_UIAppUi::HandleCommandL( TInt aCommand )
	{
	// [[[ begin generated region: do not modify [Generated Code]
	TBool commandHandled = EFalse;
	switch ( aCommand )
		{ // code to dispatch to the AppUi's menu and CBA commands is generated here
		default:
			break;
		}
	
		
	if ( !commandHandled ) 
		{
		if ( aCommand == EAknSoftkeyExit || aCommand == EEikCmdExit )
			{
			Exit();
			}
		}
	// ]]] end generated region [Generated Code]
	
	}

/** 
 * Override of the HandleResourceChangeL virtual function
 */
void CFRamI_UIAppUi::HandleResourceChangeL( TInt aType )
	{
	CAknViewAppUi::HandleResourceChangeL( aType );
	// [[[ begin generated region: do not modify [Generated Code]
	// ]]] end generated region [Generated Code]
	
	}
				
/** 
 * Override of the HandleKeyEventL virtual function
 * @return EKeyWasConsumed if event was handled, EKeyWasNotConsumed if not
 * @param aKeyEvent 
 * @param aType 
 */
TKeyResponse CFRamI_UIAppUi::HandleKeyEventL(
		const TKeyEvent& aKeyEvent,
		TEventCode aType )
	{
	// The inherited HandleKeyEventL is private and cannot be called
	// [[[ begin generated region: do not modify [Generated Contents]
	// ]]] end generated region [Generated Contents]
	
	return EKeyWasNotConsumed;
	}

/** 
 * Override of the HandleViewDeactivation virtual function
 *
 * @param aViewIdToBeDeactivated 
 * @param aNewlyActivatedViewId 
 */
void CFRamI_UIAppUi::HandleViewDeactivation( 
		const TVwsViewId& aViewIdToBeDeactivated, 
		const TVwsViewId& aNewlyActivatedViewId )
	{
	CAknViewAppUi::HandleViewDeactivation( 
			aViewIdToBeDeactivated, 
			aNewlyActivatedViewId );
	// [[[ begin generated region: do not modify [Generated Contents]
	// ]]] end generated region [Generated Contents]
	
	}

/**
 * @brief Completes the second phase of Symbian object construction. 
 * Put initialization code that could leave here. 
 */ 
void CFRamI_UIAppUi::ConstructL()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	
	BaseConstructL( EAknEnableSkin  | 
					 EAknEnableMSK ); 
	InitializeContainersL();
	// ]]] end generated region [Generated Contents]
	iRecManager = CRecognitionManager::NewL(this);
	iPlayer = CAudioPlayer::NewL();
	iImageSaver = CImageSaver::NewL(this);
	iProtector = CPhoneProtector::NewL(this);
	iMonitor = CBackgroundMonitor::NewL(iProtector);
	}

//moje
//kontrola vracania do popredia
void CFRamI_UIAppUi::HandleForegroundEventL(TBool aForeground)
{
 // Call Base class method
 CAknAppUi::HandleForegroundEventL(aForeground);

 if(aForeground && !iOwnFocus && iBack)
 {
     //aplikacia na popredi
     CConfiguration *conf = CConfiguration::NewLC();
 	 conf->LoadSettingFromFileL();
 		
 	 if(conf->iSecurityLevel == 1)
 	 {
	 CaptureImage();
 	 }
 	 CleanupStack::PopAndDestroy(conf);
 	 iBack = EFalse;
 }
 else
	 {
		 if(!aForeground)
			 iBack = ETrue;
	 }
}

void CFRamI_UIAppUi::ProtectPhone()
	{
		iOwnFocus = ETrue;
		iMonitor->DoCancel();
		iPaused = ETrue;
		
		CConfiguration *conf = CConfiguration::NewLC();
		conf->LoadSettingFromFileL();
		
		if(conf->iSecurityLevel != 1)
		{
			TApaTask task(CCoeEnv::Static()->WsSession());
			task.SetWgId( CEikonEnv::Static()->RootWin().Identifier());
			task.BringToForeground();
		}
		
		
		TBuf<50> right = conf->iPin;
		
		TBuf<50> pin;
		TInt counter = 0;
		while(counter<3 && pin.Compare(right) !=0)
		{
			pin = _L("");
			iFRamI_UIMainContainerView->RunPinQueryL(pin, ETrue);
			counter++;
		}
		
		if(pin.Compare(right) !=0) //nebolo zadane dobre pin
		{
			switch(conf->iLoudNotification)
			{
			case 1: //prehraj zvuk
				iPlayer->PlayFile(conf->iSoundFile);
				break;
			case 2: //prehraj text
				iPlayer->PlayText(_L("Hello"));
				break;
			}
			
			switch(conf->iHiddenNotification)
			{
			case 1://sms
				CMessageSender *sender = CMessageSender::NewL();
				CleanupStack::PushL(sender);
				sender->SendSmsL(conf->iPhone, _L("Vas telefon bol neopravnene pouzity. FRamI"));
				CleanupStack::PopAndDestroy(sender);
				break;
			case 2://mms
				CMessageSender *sender1 = CMessageSender::NewL();
				CleanupStack::PushL(sender1);
				sender1->SendMmsL(conf->iPhone, iLastImage);
				CleanupStack::PopAndDestroy(sender1);
				break;
			case 3://email
				CMessageSender *sender2 = CMessageSender::NewL();
				CleanupStack::PushL(sender2);
				RDebug::Print(iLastImage);
				sender2->SendMailL(conf->iMail, _L("Vas telefon bol neopravnene pouzity. FRamI"), iLastImage);
				CleanupStack::PopAndDestroy(sender2);
				break;
			}
			
			if(conf->iSecurityLevel == 2)
			{
				TApaTaskList list(CCoeEnv::Static()->WsSession());
				TApaTask task = list.FindApp(iLastRun);
				task.KillTask();
			}
		}
		if(conf->iSecurityLevel != 1)
		{
			SendToBackground();
		}
		CleanupStack::PopAndDestroy(conf);
	}

//prepinananie pohladov
void CFRamI_UIAppUi::ShowMainView()
	{
		ActivateLocalViewL(iFRamI_UIMainContainerView->Id());
	}

void CFRamI_UIAppUi::ShowSettings()
	{
		iFRamI_UISettingListView->ResetConfiguration();
		ActivateLocalViewL(iFRamI_UISettingListView->Id());
	}

void CFRamI_UIAppUi::ShowUsersAdministration()
	{
		ActivateLocalViewL(iFRamI_UIUsersListView->Id());
	}

void CFRamI_UIAppUi::ShowCamera()
	{
		ActivateLocalViewL(iFRamI_UICameraContainerView->Id());
	}

void CFRamI_UIAppUi::ShowBrowser()
	{
		ActivateLocalViewL(iFRamI_UIBrowserListView->Id());
	}

void CFRamI_UIAppUi::ShowCameraOriginView()
	{
		switch(iCameraRequester)
		{
		case 2: //dotaz pochadza z nastaveni
			iCameraRequester = 0;
			ActivateLocalViewL(iFRamI_UIUsersListView->Id());
			break;
		case 3: //dotaz pochadza z nastaveni
			iCameraRequester = 0;
			ActivateLocalViewL(iFRamI_UIMainContainerView->Id());
			break;
		}
	}

void CFRamI_UIAppUi::ShowBrowserOriginView()
	{
		switch(iBrowserRequester)
		{
		case 1: //dotaz pochadza z nastaveni
			iBrowserRequester = 0;
			ActivateLocalViewL(iFRamI_UISettingListView->Id());
			break;
		case 2: //dotaz pochadza z novych osob
			iBrowserRequester = 0;
			ActivateLocalViewL(iFRamI_UIUsersListView->Id());
			break;
		case 3: //dotaz pochadza z novych osob
			iBrowserRequester = 0;
			ActivateLocalViewL(iFRamI_UIMainContainerView->Id());
			break;
		}
	}

//settings
void CFRamI_UIAppUi::SearchForSoundFile()
	{
		iBrowserRequester = 1;
		ShowBrowser();
	}

//users
void CFRamI_UIAppUi::CaptureNewUserImage(TDesC &aName)
	{
		iCameraRequester = 2;
		iNewUserName = aName;
		ShowCamera();
	}

void CFRamI_UIAppUi::SearchForNewUserImageFile(TDesC &aName)
	{
		iBrowserRequester = 2;
		iNewUserName = aName;
		ShowBrowser();
	}

//main
void CFRamI_UIAppUi::CaptureAuthImage()
	{
		iCameraRequester = 3;
		ShowCamera();
	}

void CFRamI_UIAppUi::SearchForAuthImageFile()
	{
		iBrowserRequester = 3;
		ShowBrowser();
	}
	
//phoneprotector
void CFRamI_UIAppUi::CaptureImage(TUid aAppUid)
{
	iCameraRequester = 4;
	iLastRun = aAppUid;
	iEngine = CCamEngine::NewL(NULL, this);
	iEngine->InitCameraL();
	
	//CNokiaCVImage *image1 = CNokiaCVImage::NewL();
	//TRAPD(err1, image1->CreateL(KDefaultImage));
	//PhotoReady(*(image1->Bitmap()));
	
}

void CFRamI_UIAppUi::CaptureImage()
{
	iCameraRequester = 4;
	iEngine = CCamEngine::NewL(NULL, this);
	iEngine->InitCameraL();

	//CNokiaCVImage *image1 = CNokiaCVImage::NewL();
	//TRAPD(err1, image1->CreateL( KDefaultImage));
	//PhotoReady(*(image1->Bitmap()));
}
//browser
void CFRamI_UIAppUi::FileChosen(TDesC &aPath)
	{
		switch(iBrowserRequester)
		{
		case 1: //dotaz pochadza z nastaveni
			iBrowserRequester = 0;
			iFRamI_UISettingListView->SetPath(aPath);
			ActivateLocalViewL(iFRamI_UISettingListView->Id());
			break;
		case 2:
			iBrowserRequester = 0;
			ActivateLocalViewL(iFRamI_UIUsersListView->Id());
			CNokiaCVImage *image = CNokiaCVImage::NewL();
			TRAPD(err, image->CreateL( aPath));
			if(err == KErrNone)
				iRecManager->RecognizeAuthorized(image, iNewUserName);
				//vysledok sa dozvieme pomocou UserAdded
			break;
		case 3:
			iBrowserRequester = 0;
			iTestMode = ETrue;
			ActivateLocalViewL(iFRamI_UIMainContainerView->Id());
			CNokiaCVImage *image1 = CNokiaCVImage::NewL();
			TRAPD(err1, image1->CreateL( aPath));
			if(err1 == KErrNone)
				iRecManager->Authetificate(image1);
				//vysledok sa dozvieme pomocou UserAuthetificated
			break;
		}
	}

//camera
void CFRamI_UIAppUi::PhotoReady(const CFbsBitmap &aBitmap)
	{
		CNokiaCVImage *image;
		CFbsBitmap *bitmap;
		switch(iCameraRequester)
		{
		case 2: //dotaz pochadza z novych osob
			iCameraRequester = 0;
			ActivateLocalViewL(iFRamI_UIUsersListView->Id());
			image = CNokiaCVImage::NewL();
			bitmap = new (ELeave) CFbsBitmap;;
			bitmap->Duplicate(aBitmap.Handle());
			TRAPD(err,image->CreateL(*bitmap));
			if(err == KErrNone)
				iRecManager->RecognizeAuthorized(image, iNewUserName);
			//vysledok sa dozvieme pomocou UserAdded
			break;
		case 3: //dotaz pochadza z testovania rozpoznania
				iCameraRequester = 0;
				iTestMode = ETrue;
				ActivateLocalViewL(iFRamI_UIMainContainerView->Id());
				image = CNokiaCVImage::NewL();
				bitmap = new (ELeave) CFbsBitmap;;
				bitmap->Duplicate(aBitmap.Handle());
				TRAPD(err1, image->CreateL(*bitmap));
				if(err1 == KErrNone)
					iRecManager->Authetificate(image);
				//vysledok sa dozvieme pomocou UserAdded
				break;
		case 4: //dotaz kvoli ostremu rozpoznaniu
			iCameraRequester = 0;
			iTestMode = EFalse;
			TSize s = aBitmap.SizeInPixels();
			image = CNokiaCVImage::NewL();
			if(iLastUser)
			{
				delete iLastUser;
				iLastUser = NULL;
			}
			iLastUser = new (ELeave) CFbsBitmap;;
			iLastUser->Duplicate(aBitmap.Handle());
			TRAPD(err2, image->CreateL(*iLastUser));
			if(err2 == KErrNone)
				iRecManager->Authetificate(image);
			//vysledok sa dozvieme pomocou UserAdded
			break;
		}
	}

//RecognitionManager
void CFRamI_UIAppUi::UserAdded(TInt aResult)
	{
		HBufC* text;
		switch(aResult)
		{
		case 1://pouzivatel pridany
			text = StringLoader::LoadLC( R_APPLICATION_AKN_VIEW_USER_ADDED );
			iFRamI_UIUsersListView->RunInfoNoteL(text);
			CleanupStack::PopAndDestroy( text );
			iFRamI_UIUsersListView->Refresh();
			break;
		case 0: //pouzivatel nepridany, lebo nemohol byt vytvoreny graf
			//ActivateLocalViewL(iFRamI_UIUsersListView->Id());
			text = StringLoader::LoadLC( R_APPLICATION_AKN_VIEW_USER_NOT_ADDED );
			iFRamI_UIUsersListView->RunInfoNoteL(text);
			CleanupStack::PopAndDestroy( text );
			break;
		case -1://pouzivatel nepridany, lebo uz taky existuje
			text = StringLoader::LoadLC( R_APPLICATION_AKN_VIEW_USER_EXISTS );
			iFRamI_UIUsersListView->RunInfoNoteL(text);
			CleanupStack::PopAndDestroy( text );
			break;
		}	
	}
	
void CFRamI_UIAppUi::UserAuthetificated(TBool aResult)
	{
		if(iEngine)
		{
			delete iEngine;
			iEngine = NULL;
		}
		if(iTestMode)
		{
			HBufC* text;
			if(aResult)
				text = StringLoader::LoadLC( R_APPLICATION_AKN_VIEW_USER_AUTHETIFICATED);
			else
				text = StringLoader::LoadLC( R_APPLICATION_AKN_VIEW_USER_UNKNOWN);
			
			iFRamI_UIMainContainerView->RunAuthetificationResultL(text);
			CleanupStack::PopAndDestroy( text );
		}
		else
		{
			//v pripade pozitivnej autentifikacie nie je potrebna ziadna akcia
			if(!aResult)
			{
				iImageSaver->SaveImage(iLastUser);
				ProtectPhone();
			}
		}
	}

//ImageSaver
void CFRamI_UIAppUi::SetLastSavedImage(TFileName aFilename)
	{
		iLastImage = aFilename;
	}

void CFRamI_UIAppUi::SendToBackground()
	{
		iOwnFocus = EFalse;
		TApaTask task(CCoeEnv::Static()->WsSession());
		task.SetWgId( CEikonEnv::Static()->RootWin().Identifier());
		task.SendToBackground();
		
		CConfiguration *conf = CConfiguration::NewLC();
		conf->LoadSettingFromFileL();
		if(conf->iSecurityLevel == 2)
		{
			CArrayFixFlat<TUid> *c = new (ELeave) CArrayFixFlat<TUid>(2);
			TUid my1 = {0xEF7E8A28};
			c->AppendL(my1);
			if(iPaused)
			{
				iMonitor->Continue();
				iPaused = EFalse;
			}
			else
			{
				if(iMonitor)
					delete iMonitor;
				iMonitor = CBackgroundMonitor::NewL(iProtector);
				iMonitor->StartL(c);
			}
		}
		else if(conf->iSecurityLevel == 3)
		{
			if(iPaused)
			{
				iMonitor->Continue();
				iPaused = EFalse;
			}
			else
			{
				if(iMonitor)
					delete iMonitor;
				iMonitor = CBackgroundMonitor::NewL(iProtector);
				iMonitor->StartL();
			}
		}
		CleanupStack::PopAndDestroy(conf);
	}
